<template>
	<view>
		<!-- #ifndef MP-WEIXIN -->
		<u-navbar :is-back="false" title="购物车" :border-bottom="false" title-color="#f1f1f1" :background="navbarBackground">
			<text class="slot" slot="right" @tap="handleSlotTap">{{ isEdit ? '完成' : '管理' }}</text>
		</u-navbar>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<u-navbar :is-back="false" title="购物车" :border-bottom="false" title-color="#f1f1f1" :background="navbarBackground">
			<view class="slot">
				<text @tap="handleSlotTap">{{ isEdit ? '完成' : '管理' }}</text>
			</view>
		</u-navbar>
		<!-- #endif -->
		<view class="main">
			<view v-if="loginState">
				<!-- 购物车不为空 -->
				<view class="list" v-if="cartList.length !== 0">
					<u-checkbox-group @change="checkboxGroupChange">
						<view class="item" v-for="item in cartList" :key="item.id">
							<view class="card-left">
								<view class="checkbox">
									<u-checkbox v-model="item.checked" :name="item.goods_id" active-color="#3d6fc1" shape="circle" @change="handleItemChange($event, item)"></u-checkbox>
								</view>
								<u-image width="30vw" height="180" border-radius="10" :src="item.cover" @click="handleDetail(item.goods_id)"></u-image>
							</view>
							<view class="card-right">
								<text class="name" @click="handleDetail(item.goods_id)">{{ item.title }}</text>
								<text class="un-price">{{ '￥' + item.origin_price }}</text>
								<view class="on-price">
									<view class="price">
										<text class="symbol">￥</text>
										<text>{{ item.deposit_price }}</text>
									</view>
									<u-number-box
										:min="1"
										:max="item.stock"
										:input-width="40"
										:input-height="40"
										v-model="item.share_num && item.share_num"
										@minus="handleNumChange($event, item.id)"
										@plus="handleNumChange($event, item.id)"
									></u-number-box>
								</view>
							</view>
						</view>
					</u-checkbox-group>
					<view class="fixed">
						<view class="fixed-item">
							<u-checkbox v-model="checkall" @change="handleCheckAll" shape="circle" active-color="#3d6fc1">全选</u-checkbox>
							<view class="fixed-item-right">
								<view class="all" v-show="isEdit == false">
									合计：
									<text>{{ '￥' + allPrice }}</text>
								</view>
								<u-button v-show="isEdit == true" :custom-style="customStyle" shape="circle" size="mini" :ripple="true" ripple-bg-color="#8EB7FA" @click="handleDelete">
									删除商品
								</u-button>
								<u-button v-show="isEdit == false" :custom-style="customStyle" shape="circle" size="mini" :ripple="true" ripple-bg-color="#8EB7FA" @click="handleSubmit">
									提交订单
								</u-button>
							</view>
						</view>
					</view>
				</view>
				<!-- 购物车为空 -->
				<view class="empty" v-else>
					<u-image width="200" height="200" :src="require('../../static/image/cartnull.png')"></u-image>
					<text>购物车空空的</text>
					<u-button shape="circle" :ripple="true" ripple-bg-color="#8EB7FA" :custom-style="btnStyle" @click="handleToCart">去店铺逛逛</u-button>
				</view>
			</view>
			<view class="else" v-else>
				<u-image width="200" height="200" :src="require('../../static/image/icons.png')"></u-image>
				<view class="please"><text>您需要先登录才能查看您的购物车信息哦</text></view>
				<u-button shape="circle" open-type="getUserInfo" :ripple="true" ripple-bg-color="#8EB7FA" :custom-style="btnStyle" @click="handleToLogin">
					<u-icon style="margin-right: 15rpx;" size="50" name="weixin-fill"></u-icon>
					立即登录
				</u-button>
			</view>
		</view>
		<!-- 退出登录 -->
		<u-popup v-model="showAdd" border-radius="10" mode="center">
			<view class="popup">
				<text class="popup-title">提示</text>
				<view class="popup-content"><text>您还未添加收货地址，是否去添加？</text></view>
				<view class="popup-bottom">
					<text @tap="showAdd = false">取消</text>
					<text class="confirm" @tap="handleAddAdress">确定</text>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			navbarBackground: {
				backgroundImage: 'linear-gradient(90deg, rgb(27,52,92), rgb(49,84,142))'
			},
			btnStyle: {
				width: '60vw',
				backgroundColor: '#3d6fc1',
				color: '#f1f1f1'
			},
			customStyle: {
				backgroundColor: '#3d6fc1',
				padding: '35rpx 50rpx',
				color: '#f1f1f1',
				margin: 0
			},
			loginState: false,
			isEdit: false,
			cartList: [], // 购物车
			checked: false,
			checkall: false, // 全选
			showAdd: false, // 添加地址
			chooseArr: [],
			wx_code: ''
		};
	},
	onLoad() {
		// #ifdef MP-WEIXIN
		uni.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		// #endif
		// #ifdef H5
		this.wx_code = getUrlParams('code');
		let loginState = uni.getStorageSync('login_state');
		if (!loginState && this.wx_code) {
			this.$baseRequest(
				'/api/Login/h5Login',
				{
					code: this.wx_code
				},
				'POST'
			).then(res => {
				let token = res.data.token;
				uni.setStorageSync('tk', token);
				uni.setStorageSync('login_state', true);
				this.$nextTick(() => {
					this.handleGetList();
				});
			});
		}
		// #endif
	},
	onShow() {
		// 初始化状态
		uni.hideTabBarRedDot({ index: 2 });
		this.handleGetList();
		this.checkall = false;
		this.isEdit = false;
	},
	methods: {
		// 获取购物车列表
		handleGetList() {
			let state = uni.getStorageSync('login_state');
			this.loginState = state && state ? true : false;
			if (this.loginState) {
				this.$tkRequest('/api/ShopCar/getList').then(res => {
					this.cartList = res.data;
				});
			}
		},
		handleDetail(id) {
			uni.navigateTo({
				url: `../shop/detail/detail?id=${id}`
			});
		},
		handleSlotTap() {
			uni.showLoading({
				title: '加载中...'
			});
			setTimeout(() => {
				uni.hideLoading();
				this.isEdit = !this.isEdit;
			}, 200);
		},
		handleToCart() {
			uni.switchTab({
				url: '../shop/shop'
			});
		},
		handleAddAdress() {
			this.showAdd = false;
			uni.navigateTo({
				url: '../mine/shippingAddress/newAddress/newAddress'
			});
		},
		handleToLogin() {
			// #ifdef APP-PLUS
			uni.reLaunch({
				url: '../mine/login/login'
			});
			// #endif
			// #ifdef MP-WEIXIN
			let that = this;
			uni.login({
				provider: 'weixin',
				success: function(res) {
					let code = res.code;
					uni.getUserInfo({
						success: function(result) {
							let iv = result.iv;
							let encryptedData = result.encryptedData;
							let info = JSON.parse(result.rawData);
							let params = {
								code: code,
								iv: iv,
								encryptedData: encryptedData,
								nickName: info.nickName,
								gender: info.gender,
								avatarUrl: info.avatarUrl
							};
							uni.showLoading({
								title: '登录中...'
							});
							that.$baseRequest('/api/login/wechatLogin', params).then(res => {
								uni.hideLoading();
								let tk = res.data.token;
								uni.setStorageSync('login_state', true);
								uni.setStorageSync('tk', tk);
								uni.showToast({
									title: '登录成功',
									success: function() {
										setTimeout(() => {
											that.handleGetList();
										}, 50);
									}
								});
							});
						}
					});
				}
			});
			// #endif
			// #ifdef H5
			const appId = 'wx58859e594293179b';
			const url = 'http%3a%2f%2fzhibo.aoxiang.com%2f%23%2fpages%2fcart%2fcart';
			let ua = navigator.userAgent.toLowerCase();
			let isWeixin = ua.indexOf('micromessenger') != -1;
			// 判断是否是微信浏览器
			if (isWeixin) {
				location.href =
					'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
					appId +
					'&redirect_uri=' +
					url +
					'&response_type=code&scope=snsapi_userinfo&connect_redirect=1&state=STATE#wechat_redirect';
			} else {
				uni.showToast({
					title: '请在微信中打开',
					icon: 'none'
				});
			}
			// #endif
		},
		// 修改数量
		handleNumChange(e, id) {
			this.$tkRequest('/api/ShopCar/edit', {
				id: id,
				share_num: e.value
			}).then(res => {
				this.handleGetList();
				this.checkall = false;
			});
		},
		// 复选框组变化
		checkboxGroupChange(arr) {
			this.chooseArr = [...arr];
		},
		// 复选框状态
		handleItemChange(e, item) {
			if (typeof item.checked === 'undefined') {
				this.$set(item, 'checked', e.value);
			} else {
				item.checked = e.value;
			}
			// 全选
			if (this.cartList.every(item => item.checked == true)) {
				this.checkall = true;
			} else {
				this.checkall = false;
			}
		},
		// 全选
		handleCheckAll() {
			if (!this.checkall) {
				this.cartList.forEach(val => {
					if (typeof val.checked === 'undefined') {
						this.$set(val, 'checked', true);
					} else {
						val.checked = true;
					}
				});
				this.chooseArr = this.cartList.map(item => item.goods_id);
			} else {
				this.cartList.forEach(val => {
					if (typeof val.checked === 'undefined') {
						this.$set(val, 'checked', false);
					} else {
						val.checked = false;
					}
				});
				this.chooseArr = [];
			}
		},
		// 删除商品
		handleDelete() {
			let list = this.cartList.filter(item => {
				return item.checked == true;
			});
			let deleteList = list.map(item => item.id);
			if (deleteList.length < 1) {
				uni.showToast({
					title: '请选择要删除的商品',
					icon: 'none'
				});
				return false;
			} else {
				let _this = this;
				uni.showModal({
					title: '提示',
					content: '你确定要删除该商品吗？',
					confirmColor: '#295FB7',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '正在删除...'
							});
							_this
								.$tkRequest(
									'/api/ShopCar/delete',
									{
										ids: deleteList.toString()
									},
									'POST'
								)
								.then(res => {
									uni.hideLoading();
									_this.handleGetList();
									uni.showToast({
										title: res.msg
									});
								});
						}
					}
				});
			}
		},
		// 提交订单
		handleSubmit() {
			let submitList = this.cartList.filter(item => item.checked == true);
			if (submitList.length < 1) {
				uni.showToast({
					title: '请选择商品',
					icon: 'none'
				});
				return false;
			} else {
				this.$tkRequest('/api/Address/getList').then(res => {
					let list = res.data;
					uni.setStorageSync('chooseListInfo', JSON.stringify(submitList));
					if (list.length > 0) {
						uni.navigateTo({
							url: './order/order?from=order'
						});
					} else {
						this.showAdd = true;
					}
				});
			}
		}
	},
	computed: {
		// 计算总价
		allPrice: function() {
			/* 返回已选列表 */
			let checkedList = this.cartList.filter(item => {
				if (item.checked) {
					return item;
				}
			});
			if (checkedList.length > 0) {
				// 返回 定金*数量
				let itemPrice = checkedList.map(item => {
					return item.deposit_price * item.share_num;
				});
				// 返回总价
				return itemPrice.reduce((a, b) => a + b);
			} else {
				return 0;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.slot {
	padding: 0 $uni-spacing-row-lg;
	color: #f1f1f1;
	font-size: 12pt;
	/* #ifdef APP-PLUS */
	font-size: 14pt;
	/* #endif */
}

.main {
	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15vh $uni-spacing-row-lg;

		text {
			margin: 50rpx 0 80rpx 0;
			font-size: 12pt;
			color: #999;
		}
	}
	.else {
		padding: 20vh $uni-spacing-row-lg;
		display: flex;
		flex-direction: column;
		align-items: center;

		.please {
			padding: 100rpx 0 50rpx 0;
		}
	}

	.list {
		padding: $uni-spacing-col-lg $uni-spacing-row-lg;
		margin-bottom: 100rpx;
		background-color: #fff;
		display: flex;
		flex-direction: column;

		.item {
			width: 100%;
			display: flex;
			align-items: center;
			padding: $uni-spacing-col-base 0;

			.card-left {
				display: flex;
				align-items: center;
			}

			.card-right {
				flex: 1;
				height: 160rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				padding-left: $uni-spacing-row-sm;
				overflow: hidden;

				.name {
					font-size: 1rem;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					font-weight: bold;
				}

				.un-price {
					font-size: 9pt;
					text-decoration: line-through;
					color: #999;
				}

				.on-price {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.price {
						flex: 1;
						color: #eab952;
						font-size: 1rem;
						display: flex;
						align-items: flex-end;

						.symbol {
							white-space: nowrap;
							font-size: 10pt;
						}
					}
				}
			}
		}
	}
}

.popup {
	width: 80vw;
	padding: $uni-spacing-col-lg $uni-spacing-row-lg;
	display: flex;
	flex-direction: column;
	align-items: center;

	.popup-title {
		font-size: 12pt;
	}

	.popup-item {
		display: flex;
		align-items: center;
		padding: $uni-spacing-col-lg 0;

		.get {
			font-size: 11pt;
			color: #3f6cb7;
		}

		.time {
			font-size: 10pt;
			color: #c0c0c0;
		}
	}

	.popup-content {
		font-size: 1rem;
		padding: 40rpx 0;
	}

	.popup-bottom {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding-top: $uni-spacing-col-lg;
		font-size: 12pt;

		text {
			flex: 1;
			text-align: center;
		}

		.confirm {
			color: #3f6cb7;
		}
	}
}

.fixed {
	position: fixed;
	left: 0;
	bottom: 0;
	/* #ifdef H5 */
	bottom: 50px;
	/* #endif */
	width: 100vw;
	background-color: #fff;

	.fixed-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: $uni-spacing-col-base $uni-spacing-row-lg;

		.fixed-item-right {
			display: flex;
			align-items: center;

			.all {
				padding: 0 $uni-spacing-row-lg;
				font-size: 11pt;
				color: #999;

				text {
					color: #eab952;
					font-size: 1.1rem;
				}
			}
		}
	}
}
</style>
